package com.lxd.property.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.lxd.property.dao.DepartmentMapper;
import com.lxd.property.dao.StaffMapper;
import com.lxd.property.pojo.Staff;
import com.lxd.property.service.StaffService;

@Service("staffService")
@Transactional
public class StaffServiceImpl implements StaffService {

	@Autowired
	private StaffMapper staffMapper;
	@Autowired
	private DepartmentMapper departMapper;

	private Integer depaid;

	@Override
	public Map<String, Object> findAllStaff(Map<String, Object> map) {
		// TODO Auto-generated method stub
		Map<String, Object> resMap = new HashMap<String, Object>();

		List<Staff> list = staffMapper.findAllStaff(map);

		Long total = staffMapper.findAllStaffCount(map);

		resMap.put("rows", list);

		resMap.put("total", total);

		return resMap;
	}

	@Override
	public Integer addStaff(Staff staff) {
		// TODO Auto-generated method stub
		int i;
		if (staffMapper.addStaff(staff) == 1) {
			if (departMapper.addStaffNumber(staff.getDepaid()) == 1) {
				i = 1;
			} else {
				i = 0;
			}
		} else {
			i = 0;
		}
		return i;
	}

	@Override
	public Staff findStaffById(Integer id) {
		// TODO Auto-generated method stub
		Staff staff = staffMapper.findStaffById(id);
		depaid = staff.getDepaid();
		return staff;
	}

	@Override
	public Integer updateStaff(Staff staff) {
		// TODO Auto-generated method stub
		int i = 0;
		if (depaid == staff.getDepaid()) {
			i = staffMapper.updateStaff(staff);
		} else if (depaid != null && depaid != staff.getDepaid()) {
			if (staffMapper.updateStaff(staff) == 1) {
				if (departMapper.addStaffNumber(staff.getDepaid()) == 1
						&& departMapper.reduceStaffNumber(depaid) == 1) {
					i = 1;
				} else {
					i = 0;
					throw new RuntimeException();
				}

			} else {
				i = 0;
			}
		}
		return i;

	}

	@Override
	public Integer staffQuit(Staff staff) {
		// TODO Auto-generated method stub
		int i;
		if (staffMapper.staffQuit(staff) == 1) {
			if (departMapper.reduceStaffNumber(staff.getDepaid()) == 1) {
				i = 1;
			} else {
				i = 0;
				throw new RuntimeException();
			}
		} else {
			i = 0;
		}
		return i;
	}

}
